﻿Imports Telerik.Windows.Controls
Imports Telerik.Windows.Data
Imports CRM.BusinessLayer
Imports System.Data
Imports System.Text
Imports System.ComponentModel
Partial Public Class frmAdminProducts
    Private intSaveNeworEdit As Integer
    Private Sub frmAdminProducts_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.KeyUp
        If e.Key = Key.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub frmAdminProducts_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim progressBar As frmProgressBar = Nothing
        Try
            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads ....."
            progressBar.Show()
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            RefreshList()
            LoadCombo()
        Catch ex As Exception
        Finally
            progressBar.Close()
            progressBar = Nothing
        End Try
        Me.btnsave.IsEnabled = False
        Me.btnEdit.IsEnabled = False
        Me.btnCancel.IsEnabled = False
        Me.btnDelete.IsEnabled = False
    End Sub

    Private Sub btnAddProduct_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddProduct.Click
        intSaveNeworEdit = 1
        ClearControls()
        EnableControls(True)
        Me.btnAddProduct.IsEnabled = True
        Me.btnsave.IsEnabled = True
        Me.btnEdit.IsEnabled = True
        Me.btnCancel.IsEnabled = True
        Me.btnDelete.IsEnabled = True
        Me.txtProductName.IsEnabled = True
        Me.txtProductName.Focus()
        radILRNo.IsEnabled = False
        radILRYes.IsEnabled = False
        radUpdateUKNo.IsEnabled = False
        radUpdateUKYes.IsEnabled = False
        drpUKVisa.IsEnabled = False
        txtWeblink.IsEnabled = False
        drpDateCat.IsEnabled = False
        drpCalcSet.IsEnabled = False
        drpMFBGroup.IsEnabled = False
        drpWebLoop.IsEnabled = False
        drpFastTrack.IsEnabled = False
        drpTarget.IsEnabled = False
    End Sub

    Private Sub btnsave_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnsave.Click
        If txtProductName.Text.Trim = String.Empty Then
            MsgBox("Please enter Product Type Name !")
            txtProductName.Focus()
            Exit Sub
        ElseIf drpDestination.SelectedIndex = -1 Then
            MsgBox("Please select Destination !")
            Exit Sub
        ElseIf drpProdType2.SelectedIndex = -1 Then
            MsgBox("Please select Product Type !")
            Exit Sub
        ElseIf drpStageDiagram.SelectedIndex = -1 Then
            MsgBox("Please select StageDiagram !")
            Exit Sub
        ElseIf drpChargeGroup.SelectedIndex = -1 Then
            MsgBox("Please select Charge Group !")
            Exit Sub
        ElseIf drpEventGroup.SelectedIndex = -1 Then
            MsgBox("Please select Event Group !")
            Exit Sub
        ElseIf drpSLS.SelectedIndex = -1 Then
            MsgBox("Please select SLS !")
            Exit Sub
        Else
            btnsave.IsEnabled = False
            Dim sql As StringBuilder
            Dim productName As String = txtProductName.Text.Trim()
            Dim Product_DTEntered As String = DateTime.Now()
            Dim destinationId As Integer = drpDestination.SelectedValue
            Dim productType As Integer = drpProdType2.SelectedValue
            Dim stageDiagramId As Integer = drpStageDiagram.SelectedValue
            Dim chargeGroupId As Integer = drpChargeGroup.SelectedValue
            Dim eventGroupId As Integer = drpEventGroup.SelectedValue
            Dim slsId As Integer = drpSLS.SelectedValue
            Dim Product_EnteredBy As Integer = 1
            Dim Product_Indefinite As Integer = 1
            Dim Product_NewNatID As Integer = 1
            Dim Product_NewUKVisaID As Integer = 1
            Dim Product_NewResidenceID As Integer = 1
            Dim Product_SetTo As Integer = 1
            Dim Product_ClientType As Integer = 0
            Dim Product_Weblink As Integer = 1
            Dim Product_UKVisaID As Integer = 1
            Dim Product_IndefiniteDuration As Integer = 1
            Dim Product_MFBGroupID As Integer = 1
            Dim Product_WebLoopID As Integer = 1
            Dim Product_FastTrack As Integer = 1
            Dim Product_DTCategory As Integer = 1
            Dim Product_CalcSet As Integer = 1
            Dim Product_TargetGroupID As Integer = 1
            Dim PRODUCT_DTDISABLED As String = "''"
            Dim PRODUCT_DIYPACKID As Integer = 1
            Dim Product_Visatype As Integer = 1
            Dim Product_ISParent As Integer = 1
            Dim Product_ParentID As Integer = 1
            'Dim residenceId As Integer = drpResidence.SelectedValue
            Select Case intSaveNeworEdit
                Case 1 'new one
                    sql = New StringBuilder
                    With sql
                        .Append("")
                        .Append("insert into [GLOBAL].[dbo].[L_Products] ([Product_Name],[Product_DTEntered],[Product_EnteredBy] ,")
                        .Append("[Product_Type],[Product_Indefinite],[Product_NewNatID],[Product_NewUKVisaID],[Product_NewResidenceID],")
                        .Append("[Product_SetTo],[Product_ClientType],[Product_Weblink],[Product_UKVisaID],[Product_DestinationID],")
                        .Append("[Product_IndefiniteDuration],[Product_StageDiagramID],[Product_MFBGroupID],[Product_SLSID],[Product_ChargeGroupID],")
                        .Append("[Product_EventGroupID],[Product_WebLoopID],[Product_FastTrack],[Product_DTCategory],")
                        .Append("[Product_CalcSet],[Product_TargetGroupID],[PRODUCT_DTDISABLED],[PRODUCT_DIYPACKID],[Product_Visatype],")
                        .Append("[Product_ISParent],[Product_ParentID] )")
                        .Append(" Values('" & txtProductName.Text & "'," & "''" & "," & Product_EnteredBy & ",")
                        .Append(productType & "," & Product_Indefinite & "," & Product_NewNatID & "," & Product_NewUKVisaID & "," & Product_NewResidenceID & ",")
                        .Append(Product_SetTo & "," & Product_ClientType & "," & Product_Weblink & "," & Product_UKVisaID & "," & destinationId & ",")
                        .Append(Product_IndefiniteDuration & "," & stageDiagramId & "," & Product_MFBGroupID & "," & slsId & "," & chargeGroupId & ",")
                        .Append(eventGroupId & "," & Product_WebLoopID & "," & Product_FastTrack & "," & Product_DTCategory & ",")
                        .Append(Product_CalcSet & "," & Product_TargetGroupID & "," & PRODUCT_DTDISABLED & "," & PRODUCT_DIYPACKID & "," & Product_Visatype & ",")
                        .Append(Product_ISParent & "," & Product_ParentID)
                        .Append(")")
                    End With

                    If CommonDataFunctions.ExecuteSQL(sql.ToString) = True Then
                        RefreshList()
                        MsgBox("The new Product has been added successfully.", MsgBoxStyle.Information, "Success")
                        'Exit Sub
                    Else
                        MsgBox("There is an error adding the product to the system. Please try again or contact IT", MsgBoxStyle.Critical, "Unsuccessful")
                        'Exit Sub
                    End If
                Case 2 'existing one
                    sql = New StringBuilder
                    With sql
                        .Append("update [GLOBAL].[dbo].[L_Products]  set ")
                        .Append(" [Product_Name] = '" & Me.txtProductName.Text.Trim() & "',")
                        .Append(" [Product_Type] =" & productType & ",")
                        .Append(" [Product_DestinationID] =" & destinationId & ",")
                        .Append(" [Product_StageDiagramID] =" & stageDiagramId & ",")
                        '.Append(" [ProductType_MFBGroupID] =" & 1 & ",")
                        '.Append(" [ProductType_SLSID] =" & 1 & ",")
                        .Append(" [Product_ChargeGroupID] =" & chargeGroupId & ",")
                        .Append(" [Product_EventGroupID] =" & eventGroupId)
                        '.Append(" [ProductType_WebLoopID] =" & 1 & ",")
                        '.Append(" [ProductType_FastTrack] =" & 1 & ",")
                        '.Append(" [ProductType_DTCategory] =" & 1 & ",")
                        '.Append(" [ProductType_CalcSet] =" & 1 & ",")
                        '.Append(" [ProductType_TargetGroupID] =" & 1 & ",")
                        '.Append(" [ProductType_BranchID] =" & branchId & ",")
                        '.Append(" [PRODUCTTYPE_DTDISABLED] =" & "''" & ",")
                        '.Append(" [ProductType_ResidenceID] =" & residenceId)
                        Dim selectedRow As DataRow = grdProducts.SelectedItem
                        .Append(" where [Product_ID] = " & selectedRow(0))
                    End With

                    If CommonDataFunctions.ExecuteSQL(sql.ToString) = True Then
                        RefreshList()
                        MsgBox("The Product have been updated successfully.", MsgBoxStyle.Information, "Success")
                        'Exit Sub
                    Else
                        MsgBox("There is an error in editing the Product details. Please try again or contact IT", MsgBoxStyle.Critical, "Unsuccessful")
                        'Exit Sub
                    End If

            End Select
            ClearControls()
            EnableControls(False)
            grdProducts.IsEnabled = True
            btnCancel.IsEnabled = False
            btnAddProduct.IsEnabled = True
            btnEdit.IsEnabled = False
            btnDelete.IsEnabled = False
        End If

        EnableControls(False)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCancel.Click
        intSaveNeworEdit = 0
        ClearControls()
        EnableControls(False)
        btnsave.IsEnabled = False
        btnEdit.IsEnabled = False
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEdit.Click
        Dim selectedRow As DataRow = grdProducts.SelectedItem
        If IsNothing(selectedRow) Then
            Exit Sub
        End If
        EnableControls(True)
        btnsave.IsEnabled = True
        btnCancel.IsEnabled = True
        intSaveNeworEdit = 2
    End Sub

    Private Sub btnAddCharge_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCharge.Click
        Dim frmAddchargeIn As New frmAddCharge
        frmAddchargeIn.ShowDialog()
    End Sub

    Private Sub grdProducts_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles grdProducts.SelectionChanged
        If Me.grdProducts.SelectedItems.Count = 0 Then
            Exit Sub
        End If
        Dim myProduct As Products.ProductInfo
        Try
            myProduct = Products.GetProductInfo(Me.grdProducts.SelectedItems(0).itemarray(0).ToString)
            Me.drpProdType2.SelectedValue = myProduct.ProductTypeId
            With myProduct
                Me.txtProductName.Text = .ProductName.Trim
                Me.txtWeblink.Text = .Weblink.Trim
                If .IndefiniteLeave Then
                    Me.radILRYes.IsChecked = True
                Else
                    Me.radILRNo.IsChecked = True
                End If
                Me.drpDestination.SelectedValue = .DestinationId
                Me.drpProdType2.SelectedValue = .ProductTypeId
                Me.drpStageDiagram.SelectedValue = .StageDiagramId
                Me.drpChargeGroup.SelectedValue = .ChargeGroupId
                Me.drpEventGroup.SelectedValue = .EventGroupId
                Me.drpSLS.SelectedValue = .StockLetterSetId
                Me.drpDateCat.SelectedValue = .DateCategoryId
                Me.drpMFBGroup.SelectedValue = .MFBGroupId
                Me.drpWebLoop.SelectedValue = .WebLoopId
                Me.drpFastTrack.SelectedValue = .FastTrackId
                Me.drpTarget.SelectedValue = .TargetGroupId
                Me.drpCalcSet.SelectedValue = .CalcSetId
                'Me.ProductTypeData(Me.drpProdType.SelectedValue)
            End With
            DataBinding.BindListView(Products.GetProductCharges(0, Me.grdProducts.SelectedItems(0).itemarray(0).ToString, False), Me.lvwDefCharges)
            DataBinding.BindListView(Products.ProductDefaultDocs(Me.grdProducts.SelectedItems(0).itemarray(0).ToString), Me.lvwDocs)
            btnEdit.IsEnabled = True
            EnableControls(False)
        Catch ex As Exception
        Finally
            myProduct = Nothing
        End Try
    End Sub

    Private Sub drpProdType_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpProdType.SelectionChanged
        RefreshList()
    End Sub

    Private Sub LoadCombo()
        Dim TasksEvents As New TasksEvents
        Try
            With Me.drpProdType2
                .SelectedValuePath = "ProductType_ID"
                .DisplayMemberPath = "Product Type"
                '.ItemsSource = CType(Products.ProductTypeList(-1, 0, True), IListSource).GetList
                .ItemsSource = CType(Products.ProductTypesList(), IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpUKVisa
                .SelectedValuePath = "ukvisa_id"
                .DisplayMemberPath = "ukvisa_name"
                .ItemsSource = CType(Admin.UKVisaList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpStageDiagram
                .SelectedValuePath = "StageDiagram_ID"
                .DisplayMemberPath = "StageDiagram_Name"
                .ItemsSource = CType(Products.StageDiagramList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpChargeGroup
                .SelectedValuePath = "ChargeGroup_ID"
                .DisplayMemberPath = "ChargeGroup_Name"
                .ItemsSource = CType(Products.ChargeGroupList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpEventGroup
                .SelectedValuePath = "EventGroup_ID"
                .DisplayMemberPath = "EventGroup_Name"
                .ItemsSource = CType(TasksEvents.EventGroupList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpSLS
                .SelectedValuePath = "SLS_ID"
                .DisplayMemberPath = "SLS_Name"
                .ItemsSource = CType(Products.SLSGroupList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpDateCat
                .SelectedValuePath = "DTCat_ID"
                .DisplayMemberPath = "DTCat_Name"
                .ItemsSource = CType(Products.DateCategoryList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpCalcSet
                .SelectedValuePath = "calcset_id"
                .DisplayMemberPath = "calcset_name"
                .ItemsSource = CType(Products.CalculatorSetList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpMFBGroup
                .SelectedValuePath = "MFBGroup_ID"
                .DisplayMemberPath = "MFBGroup_Name"
                .ItemsSource = CType(Products.GetMFBGroups, IListSource).GetList
                .SelectedIndex = -1
            End With


            'With Me.drpWebLoop
            '    .SelectedValuePath = "SLS_ID"
            '    .DisplayMemberPath = "SLS_Name"
            '    .ItemsSource = CType(Products.SLSGroupList, IListSource).GetList
            '    .SelectedIndex = -1
            'End With

            With Me.drpFastTrack
                .SelectedValuePath = "DTCat_ID"
                .DisplayMemberPath = "DTCat_Name"
                .ItemsSource = CType(Products.DateCategoryList, IListSource).GetList
                .SelectedIndex = -1
            End With

            With Me.drpTarget
                .SelectedValuePath = "calcset_id"
                .DisplayMemberPath = "calcset_name"
                .ItemsSource = CType(Products.CalculatorSetList, IListSource).GetList
                .SelectedIndex = -1
            End With


            With Me.drpDestination
                .SelectedValuePath = "Country_ID"
                .DisplayMemberPath = "Country"
                .ItemsSource = CType(Admin.CountryList, IListSource).GetList()
                .SelectedIndex = -1
            End With
        Catch ex As Exception
        Finally
            TasksEvents = Nothing
        End Try
    End Sub

    Private Sub RefreshList()
        Dim StrSQL As String
        StrSQL = "select Product_ID,Product_Name from L_Products"
        'StrSQL = "SELECT Product_ID, max(Product_Name) as Product, max(IsNull([ProductType_Name],'Not in Use')) AS Type, max(Case [Product_Indefinite] when 0 then '' else 'Ind' end) AS Exp, "
        'StrSQL = StrSQL & " Sum(Defcharge_Amount) as Net, cast(Sum(Defcharge_Amount + (defcharge_amount * defcharge_vat / 100)) as money)as Gross, Sum(Defcharge_tpcost) as TP, Sum(Defcharge_amount - defcharge_tpcost) as Income "
        'StrSQL = StrSQL & " FROM L_Products LEFT OUTER JOIN"
        'StrSQL = StrSQL & " D_DefCharges ON L_Products.Product_ID = D_DefCharges.DefCharge_ProductID LEFT OUTER JOIN"
        'StrSQL = StrSQL & " L_ProductTypes ON L_Products.Product_Type = L_ProductTypes.ProductType_ID"

        'If Me.radType.IsChecked = True Then
        '    StrSQL = StrSQL & " WHERE Product_Type = " & Me.drpProdType.SelectedValue
        'End If

        'If Me.chkExcludeNIU.IsChecked = True Then

        '    If Me.radType.IsChecked = True Then
        '        StrSQL = StrSQL & " AND"
        '    Else
        '        StrSQL = StrSQL & " WHERE"
        '    End If

        '    StrSQL = StrSQL & " Product_Type > 0"
        'End If
        'StrSQL = StrSQL & " AND DefCharge_CompanyId = 0 " 'non SLA filter
        'StrSQL = StrSQL & " Group By Product_ID"
        'StrSQL = StrSQL & " ORDER BY IsNull(max([producttype_name]),'zzz'), max(Product_name)"


        Dim productList As DataTable = CommonDataFunctions.GetSQLDatatable(StrSQL.ToString())
        grdProducts.ItemsSource = productList
        grdProducts.Columns(0).IsVisible = False
        grdProducts.Columns(0).Width = New GridLength(350)
        'grdProducts.Columns(1).Width = New GridLength(250)
        'grdProducts.Columns(2).Width = New GridLength(80)
        'grdProducts.Columns(3).Width = New GridLength(80)
        'grdProducts.Columns(4).Width = New GridLength(80)
        'grdProducts.Columns(5).Width = New GridLength(80)
        'grdProducts.Columns(6).Width = New GridLength(80)

    End Sub
    
    Private Sub radType_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles radType.Checked, radType.Unchecked
        If radType.IsChecked = True Then
            With Me.drpProdType
                .SelectedValuePath = "producttype_id"
                .DisplayMemberPath = "producttype_name"
                .ItemsSource = CType(Products.ProductTypeList(-1, 0, True), IListSource).GetList
                .SelectedIndex = -1
                .IsEnabled = True
            End With
        End If
    End Sub

    Public Sub ProductTypeData(ByVal PtID As Integer)
        If PtID = 0 Then
        Else
            Dim myTab As DataTable = Products.GetProductTypeData(PtID)
            If Me.drpStageDiagram.SelectedIndex = -1 Then
                Me.drpStageDiagram.Text = myTab.Rows(0).Item("casestage")
            End If
            If Me.drpChargeGroup.SelectedIndex = -1 Then
                Me.drpChargeGroup.Text = myTab.Rows(0).Item("chargegroup")
            End If
            If Me.drpEventGroup.SelectedIndex = -1 Then
                Me.drpEventGroup.Text = myTab.Rows(0).Item("eventgroup")
            End If
            If Me.drpSLS.SelectedIndex = -1 Then
                Me.drpSLS.Text = myTab.Rows(0).Item("sls")
            End If
            If Me.drpDateCat.SelectedIndex = -1 Then
                Me.drpDateCat.Text = myTab.Rows(0).Item("dtcat")
            End If
            If Me.drpCalcSet.SelectedIndex = -1 Then
                Me.drpCalcSet.Text = myTab.Rows(0).Item("calcset")
            End If
            If Me.drpMFBGroup.SelectedIndex = -1 Then
                Me.drpMFBGroup.Text = myTab.Rows(0).Item("mfb")
            End If
            If Me.drpWebLoop.SelectedIndex = -1 Then
                Me.drpWebLoop.Text = myTab.Rows(0).Item("webloop")
            End If
            If Me.drpFastTrack.SelectedIndex = -1 Then
                Me.drpFastTrack.Text = myTab.Rows(0).Item("fasttrack")
            End If
            If Me.drpTarget.SelectedIndex = -1 Then
                Me.drpTarget.Text = myTab.Rows(0).Item("targetgroup")
            End If
        End If
    End Sub

    Private Sub ClearControls()
        Me.txtProductName.Text = String.Empty
        Me.drpProdType2.SelectedIndex = -1
        Me.drpProdType.SelectedIndex = -1
        Me.drpChargeGroup.SelectedIndex = -1
        Me.drpEventGroup.SelectedIndex = -1
        Me.drpMFBGroup.SelectedIndex = -1
        Me.drpDateCat.SelectedIndex = -1
        Me.drpCalcSet.SelectedIndex = -1
        Me.drpTarget.SelectedIndex = -1
        Me.drpUKVisa.SelectedIndex = -1
        Me.drpWebLoop.SelectedIndex = -1
        Me.drpSLS.SelectedIndex = -1
        Me.drpStageDiagram.SelectedIndex = -1
        Me.drpFastTrack.SelectedIndex = -1
        Me.drpDestination.SelectedIndex = -1
    End Sub

    Private Sub EnableControls(ByVal Value As Boolean)
        txtProductName.IsEnabled = Value
        drpProdType2.IsEnabled = Value
        'txtWeblink.IsEnabled = Value
        drpDestination.IsEnabled = Value
        'radILRNo.IsEnabled = Value
        'radILRYes.IsEnabled = Value
        'radUpdateUKNo.IsEnabled = Value
        'radUpdateUKYes.IsEnabled = Value
        'drpUKVisa.IsReadOnly = Value
        drpStageDiagram.IsEnabled = Value
        drpChargeGroup.IsEnabled = Value
        drpEventGroup.IsEnabled = Value
        drpSLS.IsEnabled = Value
        'drpDateCat.IsEnabled = Value
        'drpCalcSet.IsEnabled = Value
        'drpMFBGroup.IsEnabled = Value
        'drpWebLoop.IsEnabled = Value
    End Sub

    Private Sub btnDeleteCharge_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeleteCharge.Click

    End Sub
End Class
